<template>
  <div class="projects-container">
    <!-- 页面头部 -->
    <div v-if="!hideHeader" class="page-header">
      <div class="header-left">
        <el-button
          circle
          size="small"
          class="collapse-btn"
          @click="filterCollapsed = !filterCollapsed"
        >
          <el-icon>
            <ArrowRight v-if="filterCollapsed" />
            <ArrowLeft v-else />
          </el-icon>
        </el-button>
        <div class="header-title-wrapper">
          <h1 class="page-title">项目管理</h1>
          <p class="page-description">管理和跟踪所有项目的进度和状态</p>
        </div>
      </div>
      <div class="header-right">
        <el-button text type="primary" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button 
          v-if="canCreateProject"
          type="primary" 
          @click="handleCreateProject"
        >
          <el-icon><Plus /></el-icon>
          新建项目
        </el-button>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧筛选栏 -->
      <transition name="slide-left">
        <div v-show="!filterCollapsed" class="filter-sidebar">
          <el-card shadow="never" class="filter-card">
            <template #header>
              <div class="filter-header">
                <span class="filter-title">
                  <el-icon><Filter /></el-icon>
                  筛选条件
                </span>
                <el-button
                  text
                  size="small"
                  @click="resetFilters"
                  :loading="isResetting"
                  class="reset-all-btn"
                >
                  <el-icon><RefreshLeft /></el-icon>
                  重置
                </el-button>
              </div>
            </template>

            <div class="filter-content">
              <!-- 搜索框 -->
              <div class="filter-group">
                <div class="filter-label">
                  <el-icon><Search /></el-icon>
                  <span>搜索</span>
                </div>
                <el-input
                  v-model="searchQuery"
                  placeholder="搜索项目名称或描述"
                  clearable
                  @input="handleSearch"
                  class="filter-input"
                  size="default"
                >
                  <template #prefix>
                    <el-icon class="search-icon"><Search /></el-icon>
                  </template>
                </el-input>
              </div>

              <!-- 基础筛选 -->
              <div class="filter-group">
                <div class="filter-label">
                  <el-icon><List /></el-icon>
                  <span>基础筛选</span>
                </div>
                
                <div class="filter-item">
                  <label class="filter-item-label">项目状态</label>
                  <el-select
                    v-model="statusFilter"
                    placeholder="请选择状态"
                    clearable
                    @change="handleFilter"
                    class="filter-select"
                    size="default"
                  >
                    <el-option label="全部" value="" />
                    <el-option
                      v-for="status in projectStatusOptions"
                      :key="status.value"
                      :label="status.label"
                      :value="status.value"
                      :class="`status-option status-${status.value}`"
                    />
                  </el-select>
                </div>

                <div class="filter-item">
                  <label class="filter-item-label">优先级</label>
                  <el-select
                    v-model="priorityFilter"
                    placeholder="请选择优先级"
                    clearable
                    @change="handleFilter"
                    class="filter-select"
                    size="default"
                  >
                    <el-option label="全部" value="" />
                    <el-option
                      v-for="priority in projectPriorities"
                      :key="priority.code"
                      :label="priority.name"
                      :value="priority.code"
                      :class="`priority-option priority-${priority.code}`"
                    />
                  </el-select>
                </div>

                <div class="filter-item">
                  <label class="filter-item-label">项目类别</label>
                  <el-select
                    v-model="categoryFilter"
                    placeholder="请选择类别"
                    clearable
                    @change="handleFilter"
                    class="filter-select"
                    size="default"
                  >
                    <el-option label="全部" value="" />
                    <el-option
                      v-for="category in PROJECT_CATEGORIES"
                      :key="category.value"
                      :label="category.label"
                      :value="category.value"
                    />
                  </el-select>
                </div>
              </div>

              <!-- 高级筛选 -->
              <el-collapse v-model="activeCollapse" class="filter-collapse">
                <el-collapse-item name="advanced" title="高级筛选">
                  <template #title>
                    <div class="collapse-title">
                      <el-icon><Setting /></el-icon>
                      <span>高级筛选</span>
                    </div>
                  </template>
                  
                  <div class="filter-item">
                    <label class="filter-item-label">项目负责人</label>
                    <el-select
                      v-model="managerFilter"
                      placeholder="请选择负责人"
                      clearable
                      @change="handleFilter"
                      class="filter-select"
                      size="default"
                      filterable
                    >
                      <el-option label="全部" value="" />
                      <el-option
                        v-for="user in users"
                        :key="user.id"
                        :label="user.name"
                        :value="user.id"
                      />
                    </el-select>
                  </div>

                  <div class="filter-item">
                    <label class="filter-item-label">日期范围</label>
                    <el-date-picker
                      v-model="dateRangeFilter"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      @change="handleFilter"
                      class="filter-date"
                      size="default"
                      style="width: 100%"
                    />
                  </div>

                  <div class="filter-item">
                    <label class="filter-item-label">归档状态</label>
                    <el-select
                      v-model="archivedFilter"
                      placeholder="请选择归档状态"
                      clearable
                      @change="handleFilter"
                      class="filter-select"
                      size="default"
                    >
                      <el-option label="全部" value="" />
                      <el-option label="已归档" :value="true" />
                      <el-option label="未归档" :value="false" />
                    </el-select>
                  </div>
                </el-collapse-item>
              </el-collapse>

              <!-- 操作按钮 -->
              <div class="filter-actions">
                <el-button 
                  v-if="canExportProject"
                  type="primary" 
                  @click="exportProjects"
                  class="export-btn"
                  :loading="isExporting"
                  block
                >
                  <el-icon><Download /></el-icon>
                  导出项目
                </el-button>
                <el-tooltip 
                  v-else
                  content="您没有导出项目的权限"
                  placement="top"
                >
                  <el-button 
                    type="primary" 
                    class="export-btn"
                    disabled
                    block
                  >
                    <el-icon><Download /></el-icon>
                    导出项目
                  </el-button>
                </el-tooltip>
              </div>
            </div>
          </el-card>
        </div>
      </transition>

      <!-- 右侧主内容区 -->
      <div class="content-area" :class="{ 'full-width': filterCollapsed }">
        <!-- 项目列表 -->
        <div class="projects-list">
          <!-- 初始加载状态 -->
          <PageLoading 
            v-if="initialLoading"
            :title="isRefreshing ? '正在刷新项目数据' : '正在加载项目数据'"
            :subtitle="isRefreshing ? '请稍候，正在更新数据...' : '请稍候，正在为您准备数据...'"
          />
          <el-card v-else v-loading="loading">
            <template #header>
              <div class="card-header">
                <div class="header-left">
                  <span>项目列表</span>
                  <el-button 
                    v-if="showCreateButton && canCreateProject"
                    type="primary" 
                    size="small"
                    @click="handleCreateProject"
                    class="create-project-btn"
                  >
                    <el-icon><Plus /></el-icon>
                    新建项目
                  </el-button>
                </div>
                <div class="view-controls">
                  <el-radio-group v-model="viewMode" size="small" class="view-mode-switcher">
                    <el-radio-button label="card">卡片视图</el-radio-button>
                    <el-radio-button label="table">表格视图</el-radio-button>
                  </el-radio-group>
                </div>
              </div>
            </template>

            <!-- 卡片视图 -->
            <div v-if="viewMode === 'card'" class="card-view">
          <el-empty v-if="projects.length === 0" description="暂无项目数据" />
          <el-row v-else :gutter="12">
            <el-col
              v-for="project in projects"
              :key="project.id"
              :span="6"
              class="project-card-col"
            >
              <el-card class="project-card project-card-hover" :body-style="{ padding: '16px' }">
                <div class="project-header">
                  <div class="project-title-wrapper">
                    <div class="project-title" @click.stop="handleViewProject(project.id)">{{ project.name }}</div>
                    <el-button
                      v-if="project.is_pinned"
                      :icon="StarFilled"
                      size="small"
                      text
                      type="warning"
                      class="pin-button pin-button-active"
                      @click.stop="handleTogglePin(project)"
                      title="取消置顶"
                    />
                    <el-button
                      v-else
                      :icon="Star"
                      size="small"
                      text
                      class="pin-button pin-button-inactive"
                      @click.stop="handleTogglePin(project)"
                      title="置顶项目"
                    />
                  </div>
                  <div class="project-status-tags">
                    <el-tag :type="getStatusType(project.status)" size="small" effect="plain">
                      {{ getStatusText(project.status) }}
                    </el-tag>
                    <el-tag v-if="project.is_archived" type="info" size="small" effect="plain">
                      已归档
                    </el-tag>
                  </div>
                </div>
                
                <div class="project-description">
                  {{ project.description || '暂无描述' }}
                </div>
                
                <div class="project-meta-compact">
                  <div class="meta-row">
                    <div class="meta-item-compact">
                      <el-icon size="14"><User /></el-icon>
                      <span>{{ project.member_count || 0 }}人</span>
                    </div>
                    <div class="meta-item-compact">
                      <el-icon size="14"><Clock /></el-icon>
                      <span>{{ project.completed_task_count || 0 }}/{{ project.task_count || 0 }}</span>
                    </div>
                  </div>
                  <div class="meta-row">
                    <div class="meta-item-compact">
                      <el-icon size="14"><Calendar /></el-icon>
                      <span>{{ formatDate(project.end_date) }}</span>
                    </div>
                    <el-tag :type="getPriorityType(project.priority)" size="small" effect="plain" class="priority-tag">
                      {{ getPriorityText(project.priority) }}
                    </el-tag>
                  </div>
                </div>
                
                <!-- 项目标签 -->
                <div v-if="project.tags && project.tags.length > 0" class="project-tags">
                  <el-tag
                    v-for="tag in project.tags.slice(0, 2)"
                    :key="tag"
                    size="small"
                    type="info"
                    effect="light"
                    class="tag-item"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-tag v-if="project.tags.length > 2" size="small" type="info" effect="light">
                    +{{ project.tags.length - 2 }}
                  </el-tag>
                </div>
                
                <div class="project-progress">
                  <div class="progress-label">
                    <span>进度</span>
                    <span class="progress-percentage">{{ Math.round(calculateProjectProgress(project)) }}%</span>
                  </div>
                  <el-progress 
                    :percentage="Math.round(calculateProjectProgress(project))" 
                    :show-text="false" 
                    :color="getProgressColor(calculateProjectProgress(project))"
                    :stroke-width="5"
                  />
                </div>
                
                <div class="project-actions">
                  <el-button size="small" text @click.stop="handleViewProject(project.id)">
                    查看
                  </el-button>
                  <el-button 
                    v-if="canUpdateProject"
                    size="small" 
                    text 
                    @click.stop="handleEditProject(project)"
                  >
                    编辑
                  </el-button>
                  <el-dropdown 
                    v-if="canUpdateProject || canDeleteProject || canArchiveProject || canUnarchiveProject || canManageMembers"
                    @command="(command) => handleProjectAction(command, project)" 
                    trigger="click"
                  >
                    <el-button size="small" text>
                      <el-icon><MoreFilled /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item 
                          v-if="canManageMembers"
                          command="members"
                        >
                          成员管理
                        </el-dropdown-item>
                        <el-dropdown-item 
                          v-if="canArchiveProject && !project.is_archived"
                          command="archive"
                        >
                          归档项目
                        </el-dropdown-item>
                        <el-dropdown-item 
                          v-if="canUnarchiveProject && project.is_archived"
                          command="restore"
                        >
                          恢复项目
                        </el-dropdown-item>
                        <el-dropdown-item 
                          v-if="canDeleteProject"
                          command="delete" 
                          divided
                        >
                          删除项目
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

            <!-- 表格视图 -->
            <div v-else class="table-view">
          <el-table
            :data="projects"
            :style="{ width: '100%' }"
          >
            <el-table-column prop="name" label="项目名称" min-width="200">
              <template #default="{ row }">
                <div class="project-name-cell">
                  <div class="name-wrapper">
                    <el-button
                      v-if="row.is_pinned"
                      :icon="StarFilled"
                      size="small"
                      text
                      type="warning"
                      class="pin-button-table pin-button-active"
                      @click.stop="handleTogglePin(row)"
                      title="取消置顶"
                    />
                    <el-button
                      v-else
                      :icon="Star"
                      size="small"
                      text
                      class="pin-button-table pin-button-inactive"
                      @click.stop="handleTogglePin(row)"
                      title="置顶项目"
                    />
                    <span class="name project-title-link" @click.stop="handleViewProject(row.id)">{{ row.name }}</span>
                  </div>
                  <el-tag :type="getPriorityType(row.priority)" size="small">
                    {{ getPriorityText(row.priority) }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="category" label="类别" width="120">
              <template #default="{ row }">
                {{ getCategoryText(row.category) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <div style="display: flex; align-items: center; gap: 6px;">
                  <el-tag :type="getStatusType(row.status)" size="small">
                    {{ getStatusText(row.status) }}
                  </el-tag>
                  <el-tag v-if="row.is_archived" type="info" size="small" effect="plain">
                    已归档
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="progress" label="进度" width="120">
              <template #default="{ row }">
                <div class="progress-cell">
                  <el-progress :percentage="Math.round(calculateProjectProgress(row))" :show-text="false" />
                  <span class="progress-text">{{ Math.round(calculateProjectProgress(row)) }}%</span>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="task_count" label="任务" width="100">
              <template #default="{ row }">
                <span>{{ row.completed_task_count || 0 }}/{{ row.task_count || 0 }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="member_count" label="成员" width="80">
              <template #default="{ row }">
                {{ row.member_count || 0 }}
              </template>
            </el-table-column>
            
            <el-table-column label="负责人" width="120">
              <template #default="{ row }">
                {{ getManagerName(row.owner_id) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="budget" label="预算" width="120">
              <template #default="{ row }">
                <span v-if="row.budget">¥{{ row.budget.toLocaleString() }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="estimated_hours" label="预估工时" width="100">
              <template #default="{ row }">
                <span v-if="row.estimated_hours">{{ row.estimated_hours }}h</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="start_date" label="开始日期" width="120">
              <template #default="{ row }">
                {{ formatDate(row.start_date) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="end_date" label="结束日期" width="120">
              <template #default="{ row }">
                {{ formatDate(row.end_date) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="tags" label="标签" width="150">
              <template #default="{ row }">
                <div v-if="row.tags && row.tags.length > 0" class="tags-cell">
                  <el-tag
                    v-for="tag in row.tags.slice(0, 2)"
                    :key="tag"
                    size="small"
                    type="info"
                    class="tag-item"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-tag v-if="row.tags.length > 2" size="small" type="info">
                    +{{ row.tags.length - 2 }}
                  </el-tag>
                </div>
                <span v-else>-</span>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button 
                  v-if="canUpdateProject"
                  size="small" 
                  @click.stop="handleEditProject(row)"
                >
                  编辑
                </el-button>
                <el-button size="small" type="primary" @click.stop="handleViewProject(row.id)">
                  查看
                </el-button>
                <el-dropdown 
                  v-if="canUpdateProject || canDeleteProject || canArchiveProject || canUnarchiveProject || canManageMembers"
                  @command="(command) => handleProjectAction(command, row)"
                >
                  <el-button size="small" type="info">
                    更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item 
                        v-if="canManageMembers"
                        command="members"
                      >
                        成员管理
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="canArchiveProject && !row.is_archived"
                        command="archive"
                      >
                        归档项目
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="canUnarchiveProject && row.is_archived"
                        command="restore"
                      >
                        恢复项目
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="canDeleteProject"
                        command="delete" 
                        divided
                      >
                        删除项目
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </div>

            <!-- 分页 -->
            <div class="pagination-wrapper">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 项目对话框组件 -->
    <ProjectDialog @success="handleProjectDialogSuccess" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { usePermission } from '@/hooks/usePermission'

// Props
interface Props {
  hideHeader?: boolean
  showCreateButton?: boolean
}
const props = withDefaults(defineProps<Props>(), {
  hideHeader: false,
  showCreateButton: false
})

// 使用 props，避免 lint 警告
const { hideHeader, showCreateButton } = props

// 定义事件
const emit = defineEmits<{
  'create-project': []
}>()
import { 
  Plus, Search, Calendar, User, ArrowDown, Clock, ArrowLeft, ArrowRight,
  MoreFilled, Star, StarFilled, Refresh, Filter,
  List, Setting, Download, RefreshLeft
} from '@element-plus/icons-vue'
import { 
  getProjectList, 
  deleteProject, 
  archiveProject,
  restoreProject,
  pinProject,
  unpinProject
} from '@/api/project'
import { ResponseParser } from '@/utils/responseParser'
import type { 
  Project, 
  ProjectStatus,
  ProjectCategory
} from '@/types/project'
import type { User as UserType } from '@/types/user'
import { getUsers } from '@/api/user'
import { PROJECT_CATEGORIES } from '@/types/project'
import { ModuleType } from '@/types/core'
import { useProjectStatsStore } from '@/stores/projectStats'
import { useStateStore } from '@/stores/state'
import { priorityApi } from '@/api/priority'
import ProjectDialog from '@/components/projects/ProjectDialog.vue'
import { useProjectDialogStore } from '@/stores/projectDialog'
import PageLoading from '@/components/ui/PageLoading.vue'
import { calculateProjectProgress as calculateProgress } from '@/utils/projectProgress'

// 路由
const router = useRouter()

// 权限检查
const { hasPermission } = usePermission()

// 权限计算属性
const canCreateProject = computed(() => hasPermission('project:create') || hasPermission('PROJECT_CREATE'))
const canUpdateProject = computed(() => hasPermission('project:update') || hasPermission('PROJECT_UPDATE') || hasPermission('project:update_all') || hasPermission('PROJECT_UPDATE_ALL'))
const canDeleteProject = computed(() => hasPermission('project:delete') || hasPermission('PROJECT_DELETE'))
const canArchiveProject = computed(() => hasPermission('project:archive') || hasPermission('PROJECT_ARCHIVE'))
const canUnarchiveProject = computed(() => hasPermission('project:unarchive') || hasPermission('PROJECT_UNARCHIVE'))
const canManageMembers = computed(() => hasPermission('project:manage_members') || hasPermission('PROJECT_MANAGE_MEMBERS'))
const canExportProject = computed(() => hasPermission('project:export') || hasPermission('PROJECT_EXPORT'))

// 响应式数据
const searchQuery = ref('')
const statusFilter = ref<ProjectStatus | ''>('')
const priorityFilter = ref<string>('')
const categoryFilter = ref<ProjectCategory | ''>('')
const viewMode = ref('card')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const initialLoading = ref(true)
const isRefreshing = ref(false)
const projectDialogStore = useProjectDialogStore()
const filterCollapsed = ref(false)
const activeCollapse = ref<string[]>([])

// 项目优先级选项（动态）
const projectPriorities = ref<Array<{ code: string; name: string; color: string }>>([])

// 获取优先级列表
const fetchPriorities = async () => {
  try {
    const response = await priorityApi.getAll(ModuleType.PROJECT)
    console.log('获取优先级API响应:', response)
    
    // 处理响应数据格式
    let prioritiesData = []
    if (response && response.data) {
      // 检查是否是统一API响应格式
      if (response.data.success && response.data.data) {
        prioritiesData = response.data.data
      } else if (Array.isArray(response.data)) {
        // 如果直接返回数组
        prioritiesData = response.data
      } else if (response.data.data && Array.isArray(response.data.data)) {
        prioritiesData = response.data.data
      }
    }
    
    if (prioritiesData && prioritiesData.length > 0) {
      projectPriorities.value = prioritiesData.map((p: any) => ({
        code: p.code,
        name: p.name,
        color: p.color || '#909399'
      }))
      console.log('解析后的优先级列表:', projectPriorities.value)
      
    } else {
      console.warn('优先级列表为空，可能数据库中还未归属项目优先级数据')
      projectPriorities.value = []
    }
  } catch (error) {
    console.error('获取优先级列表失败:', error)
    ElMessage.error('获取优先级列表失败，请检查网络连接')
    projectPriorities.value = []
  }
}

// 高级筛选相关状态
const managerFilter = ref('')
const dateRangeFilter = ref<[string, string] | null>(null)
const archivedFilter = ref<boolean | ''>(false)  // 默认只显示未归档项目
const isResetting = ref(false)
const isExporting = ref(false)

// 项目列表数据
const projects = ref<Project[]>([])
// 用户列表数据 - 用于选择项目负责人
const users = ref<UserType[]>([])
const userMap = computed(() => {
  const map = new Map<string, UserType>()
  users.value.forEach(user => {
    if (user?.id) {
      map.set(user.id, user)
    }
  })
  return map
})

// 项目统计数据 - 使用 Pinia store（保留用于刷新统计数据）
const projectStatsStore = useProjectStatsStore()
const stateStore = useStateStore()



// 计算项目进度（使用统一的进度计算函数，与后端逻辑保持一致）
const calculateProjectProgress = (project: Project): number => {
  return calculateProgress({
    requirement_count: project.requirement_count,
    requirement_completed_count: project.requirement_completed_count,
    task_count: project.task_count,
    completed_task_count: project.completed_task_count,
    defect_count: project.defect_count,
    resolved_defect_count: project.resolved_defect_count,
    test_case_count: project.test_case_count,
    passed_test_case_count: project.passed_test_case_count,
    project_status: project.status,
    start_date: project.start_date,
    end_date: project.end_date,
    progress: project.progress
  })
}

// 根据进度获取颜色
const getProgressColor = (progress: number) => {
  if (progress >= 90) return '#67c23a';
  if (progress >= 60) return '#e6a23c';
  if (progress >= 30) return '#f56c6c';
  return '#909399';
};


// 项目状态选项 - 使用状态管理store
const projectStatusOptions = computed(() => {
  console.log('计算项目状态选项 - stateStore.states:', stateStore.states)
  const projectStates = stateStore.getStatesByModule(ModuleType.PROJECT)
  console.log('获取到的项目状态数据:', projectStates)
  const options = projectStates.map(state => ({
    value: state.code,
    label: state.name,
    color: state.color || '#909399'
  }))
  console.log('转换后的状态选项:', options)
  return options
})





// 获取用户列表
const fetchUsers = async () => {
  try {
    const pageSize = 200
    let page = 1
    const collected = new Map<string, UserType>()
    let total = Infinity

    while ((page - 1) * pageSize < total) {
      const response = await getUsers({ page, size: pageSize })
      let items: UserType[] = []
      // 处理响应数据，支持多种格式
      if (response && typeof response === 'object') {
        // 检查是否是分页响应格式 { items: [], total: number, page: number, size: number }
        if ('items' in response && 'total' in response) {
          items = (response.items as UserType[]) || []
          total = typeof (response as any).total === 'number' ? (response as any).total : items.length
        }
        // 检查是否是 API 响应格式 { success: boolean, data: PaginationResponse<User> }
        else if ('data' in response && response.data && typeof response.data === 'object') {
          const data = (response as any).data
          if ('items' in data || Array.isArray(data)) {
            items = Array.isArray(data) ? data : (data.items as UserType[]) || []
            total = typeof data.total === 'number' ? data.total : items.length
          }
        }
        // 检查是否是数组格式
        else if (Array.isArray(response)) {
          items = response as UserType[]
          total = items.length
        } else {
          items = []
          total = 0
        }
      } else if (Array.isArray(response)) {
        items = response as UserType[]
        total = items.length
      } else {
        items = []
        total = 0
      }

      items.forEach(user => {
        if (user?.id) {
          collected.set(user.id, user)
        }
      })

      if (items.length < pageSize) {
        break
      }
      page += 1
    }

    users.value = Array.from(collected.values())
  } catch (error) {
    console.error('获取用户列表失败:', error)
    users.value = []
    ElMessage.error('获取用户列表失败')
  }
}

// 根据ID获取负责人名称
const getManagerName = (ownerId: string | undefined): string => {
  if (!ownerId) return '未设置'
  const cachedUser = userMap.value.get(ownerId)
  if (cachedUser) {
    return cachedUser.name || cachedUser.username || '未知'
  }
  const member = projects.value
    .flatMap(project => (project.members || []) as Array<Record<string, any>>)
    .find(m => {
      const memberId = typeof m.user_id === 'string' ? m.user_id : String(m.user_id)
      return memberId === ownerId
    })
  if (member) {
    return member.user_name || member.name || member.username || '未知成员'
  }
  return '未知成员'
}

// 获取项目列表
const fetchProjects = async (isRefresh = false) => {
  if (isRefresh) {
    isRefreshing.value = true
    initialLoading.value = true
  }
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      search: searchQuery.value || undefined,
      status: statusFilter.value || undefined,
      priority: priorityFilter.value || undefined,
      category: categoryFilter.value || undefined,
      // 高级筛选参数
      created_by: managerFilter.value || undefined,
      is_archived: archivedFilter.value === '' ? undefined : archivedFilter.value,
      // 日期范围参数
      start_date: dateRangeFilter.value?.[0] || undefined,
      end_date: dateRangeFilter.value?.[1] || undefined
    }
    
    const response = await getProjectList(params)
    console.log('项目列表API响应:', response)
    
    // 使用公共解析方法处理响应数据
    const parsedResult = ResponseParser.parseProjectListResponse(response)
    console.log('解析后的项目列表数据:', parsedResult)
    
    // 确保每个项目都有 is_pinned 字段，默认为 false
    const items = (parsedResult.items || []).map((project: Project) => ({
      ...project,
      is_pinned: project.is_pinned ?? false
    }))
    
    projects.value = items
    total.value = parsedResult.total || 0
    
    // 如果当前页面没有数据了，且不是第一页，自动跳转到第一页并重新获取
    if (items.length === 0 && currentPage.value > 1 && total.value > 0) {
      // 计算应该跳转到的页码（最后一页）
      const maxPage = Math.ceil(total.value / pageSize.value)
      if (maxPage > 0 && currentPage.value > maxPage) {
        currentPage.value = maxPage
        // 重新获取数据（避免递归，使用 setTimeout）
        setTimeout(() => {
          fetchProjects(isRefresh)
        }, 0)
        return
      }
    }
    
  } catch (error) {
    console.error('获取项目列表失败:', error)
    // 项目数据加载失败时设置为空数组，不使用备用数据
    projects.value = []
    total.value = 0
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
    if (isRefresh) {
      setTimeout(() => {
        initialLoading.value = false
        isRefreshing.value = false
      }, 300)
    } else if (initialLoading.value) {
      initialLoading.value = false
    }
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchProjects()
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
  fetchProjects()
}

// 重置筛选
const resetFilters = async () => {
  isResetting.value = true
  try {
    // 重置所有筛选条件
    searchQuery.value = ''
    statusFilter.value = ''
    priorityFilter.value = ''
    categoryFilter.value = ''
    managerFilter.value = ''
    dateRangeFilter.value = null
    archivedFilter.value = false  // 重置为默认值：只显示未归档项目
    currentPage.value = 1
    
    // 添加短暂延迟以显示加载状态
    await new Promise(resolve => setTimeout(resolve, 300))
    fetchProjects()
    
    ElMessage.success('筛选条件已重置')
  } catch (error) {
    ElMessage.error('重置筛选条件失败')
  } finally {
    isResetting.value = false
  }
}

// 导出项目
const exportProjects = async () => {
  isExporting.value = true
  try {
    // 模拟导出操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('项目导出成功')
  } catch (error) {
    ElMessage.error('导出失败，请重试')
  } finally {
    isExporting.value = false
  }
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchProjects()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchProjects()
}

// 创建项目
const handleCreateProject = () => {
  if (showCreateButton) {
    // 如果是从父组件传入的，触发事件
    emit('create-project')
  } else {
    // 否则使用原有的对话框方式
    projectDialogStore.openCreateDialog()
  }
}

// 编辑项目
const handleEditProject = (project: Project) => {
  if (!canUpdateProject.value) {
    ElMessage.warning('您没有编辑项目的权限')
    return
  }
  projectDialogStore.openEditDialog(project.id)
}

// 处理打开编辑（别名方法，用于兼容某些组件或动态调用）
// 确保在模板渲染前定义，避免运行时错误
// 使用函数声明而不是 const，确保在作用域提升时可用
// @ts-expect-error - 可能被动态调用或通过事件绑定使用，TypeScript无法静态检测
function handleOpenEdit(project: Project) {
  handleEditProject(project)
}

// 查看项目详情
const handleViewProject = (projectId: string) => {
  router.push(`/projects/${projectId}`)
}

// 项目操作处理
const handleTogglePin = async (project: Project) => {
  try {
    const wasPinned = project.is_pinned
    if (wasPinned) {
      // 取消置顶
      const response = await unpinProject(project.id)
      if (response?.success !== false) {
        project.is_pinned = false
        ElMessage.success('已取消置顶')
      }
    } else {
      // 置顶
      const response = await pinProject(project.id)
      if (response?.success !== false) {
        project.is_pinned = true
        ElMessage.success('已置顶项目')
      }
    }
    // 重新加载项目列表以更新排序
    await fetchProjects()
  } catch (error: any) {
    console.error('置顶操作失败:', error)
    // 如果后端返回成功但前端状态不同步，尝试重新加载
    if (error?.response?.status === 200 || error?.response?.data?.success) {
      await fetchProjects()
    } else {
      ElMessage.error(error?.response?.data?.message || error?.message || '操作失败')
    }
  }
}

const handleProjectAction = async (command: string, project: Project) => {
  switch (command) {
    case 'members':
      if (!canManageMembers.value) {
        ElMessage.warning('您没有管理项目成员的权限')
        return
      }
      router.push(`/projects/${project.id}/members`)
      break
    case 'archive':
      if (!canArchiveProject.value) {
        ElMessage.warning('您没有归档项目的权限')
        return
      }
      await handleArchiveProject(project)
      break
    case 'restore':
      if (!canUnarchiveProject.value) {
        ElMessage.warning('您没有恢复项目的权限')
        return
      }
      await handleRestoreProject(project)
      break
    case 'delete':
      if (!canDeleteProject.value) {
        ElMessage.warning('您没有删除项目的权限')
        return
      }
      await handleDeleteProject(project)
      break
  }
}

// 归档项目
const handleArchiveProject = async (project: Project) => {
  try {
    await ElMessageBox.confirm(
      `确定要归档项目 "${project.name}" 吗？归档后项目将不再显示在活跃项目列表中，但可以通过筛选查看。`,
      '确认归档',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await archiveProject(project.id)
    if (response?.success) {
      ElMessage.success('项目已归档')
      
      // 如果当前筛选条件是只显示未归档项目，且当前页面可能没有数据了，跳转到第一页
      if (archivedFilter.value === false && projects.value.length === 1) {
        currentPage.value = 1
      }
      
      // 刷新项目列表和统计数据
      await Promise.all([
        fetchProjects(),
        projectStatsStore.refreshStats().catch(err => {
          console.error('刷新统计数据失败:', err)
        })
      ])
    } else {
      const errorMsg = response?.message || '归档项目失败'
      ElMessage.error(errorMsg)
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('归档项目失败:', error)
      const errorMsg = error?.response?.data?.message || error?.message || '归档项目失败'
      ElMessage.error(errorMsg)
    }
  }
}

// 恢复项目
const handleRestoreProject = async (project: Project) => {
  try {
    await ElMessageBox.confirm(
      `确定要恢复项目 "${project.name}" 吗？恢复后项目将重新显示在活跃项目列表中。`,
      '确认恢复',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    const response = await restoreProject(project.id)
    if (response?.success) {
      ElMessage.success('项目已恢复')
      
      // 如果当前筛选条件是只显示已归档项目，且当前页面可能没有数据了，跳转到第一页
      if (archivedFilter.value === true && projects.value.length === 1) {
        currentPage.value = 1
      }
      
      // 刷新项目列表和统计数据
      await Promise.all([
        fetchProjects(),
        projectStatsStore.refreshStats().catch(err => {
          console.error('刷新统计数据失败:', err)
        })
      ])
    } else {
      const errorMsg = response?.message || '恢复项目失败'
      ElMessage.error(errorMsg)
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('恢复项目失败:', error)
      const errorMsg = error?.response?.data?.message || error?.message || '恢复项目失败'
      ElMessage.error(errorMsg)
    }
  }
}

// 删除项目
const handleDeleteProject = async (project: Project) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除项目 "${project.name}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    await deleteProject(project.id)
    ElMessage.success('项目已删除')
    
    // 如果当前页面没有数据了，跳转到第一页
    if (projects.value.length === 1) {
      currentPage.value = 1
    }
    
    // 刷新项目列表和统计数据
    await Promise.all([
      fetchProjects(),
      projectStatsStore.refreshStats().catch(err => {
        console.error('刷新统计数据失败:', err)
      })
    ])
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除项目失败:', error)
      ElMessage.error('删除项目失败')
    }
  }
}

// 刷新项目列表
const handleRefresh = async () => {
  try {
    // 刷新项目列表和统计数据
    await Promise.all([
      fetchProjects(true),
      projectStatsStore.refreshStats().catch(err => {
        console.error('刷新统计数据失败:', err)
      })
    ])
    ElMessage.success('刷新成功')
  } catch (error) {
    console.error('刷新失败:', error)
    ElMessage.error('刷新失败，请重试')
  }
}

// 项目对话框成功回调
const handleProjectDialogSuccess = async () => {
  // 刷新项目列表和统计数据
  await Promise.all([
    fetchProjects(),
    projectStatsStore.refreshStats().catch(err => {
      console.error('刷新统计数据失败:', err)
    })
  ])
}

// 格式化日期
const formatDate = (dateString: string | null | undefined) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取状态类型 - 从状态管理系统动态获取
const getStatusType = (status: ProjectStatus): 'info' | 'success' | 'warning' | 'danger' => {
  // 从状态管理系统获取状态信息
  const state = stateStore.getStateByCode(status, ModuleType.PROJECT)
  if (state) {
    // 根据状态名称或代码判断类型
    const name = state.name?.toLowerCase() || ''
    const code = state.code?.toLowerCase() || ''
    if (name.includes('完成') || name.includes('已完成') || code.includes('completed') || code.includes('done')) {
      return 'success'
    }
    if (name.includes('进行') || name.includes('进行中') || code.includes('active') || code.includes('in_progress')) {
      return 'success'
    }
    if (name.includes('暂停') || name.includes('挂起') || code.includes('hold') || code.includes('pause')) {
      return 'warning'
    }
    if (name.includes('取消') || name.includes('已取消') || code.includes('cancelled') || code.includes('cancel')) {
      return 'danger'
    }
    if (name.includes('归档') || name.includes('已归档') || code.includes('archived')) {
      return 'info'
    }
  }
  return 'info'
}

// 获取状态文本 - 从状态管理系统动态获取
const getStatusText = (status: ProjectStatus) => {
  // 从状态管理系统获取状态信息
  const state = stateStore.getStateByCode(status, ModuleType.PROJECT)
  if (state) {
    return state.name || status
  }
  // 如果没有找到，返回原始状态值
  return status
}

// 获取优先级类型
const getPriorityType = (priority: string): 'info' | 'warning' | 'danger' | 'success' | 'primary' => {
  if (!priority || !projectPriorities.value || projectPriorities.value.length === 0) {
    return 'info'
  }
  
  const priorityOption = projectPriorities.value.find(p => p.code === priority)
  if (!priorityOption) {
    console.warn(`未找到优先级代码: ${priority}，可用的优先级:`, projectPriorities.value.map(p => p.code))
    return 'info'
  }
  
  // 根据优先级颜色映射Element Plus类型
  const color = priorityOption.color.toLowerCase()
  if (color.includes('#f56c6c') || color.includes('red') || color.includes('danger')) {
    return 'danger'
  } else if (color.includes('#e6a23c') || color.includes('orange') || color.includes('warning')) {
    return 'warning'
  } else if (color.includes('#67c23a') || color.includes('green') || color.includes('success')) {
    return 'success'
  } else if (color.includes('#409eff') || color.includes('blue') || color.includes('primary')) {
    return 'primary'
  }
  return 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  if (!priority) {
    return '未设置'
  }
  
  if (!projectPriorities.value || projectPriorities.value.length === 0) {
    console.warn('优先级列表为空，无法显示优先级名称')
    return priority
  }
  
  const priorityOption = projectPriorities.value.find(p => p.code === priority)
  if (priorityOption) {
    return priorityOption.name
  }
  
  console.warn(`未找到优先级代码: ${priority}，可用的优先级:`, projectPriorities.value.map(p => p.code))
  return priority
}

// 获取类别文本
const getCategoryText = (category: ProjectCategory) => {
  const categoryMap = {
    web_development: 'Web开发',
    mobile_app: '移动应用',
    desktop_app: '桌面应用',
    api_development: 'API开发',
    data_analysis: '数据分析',
    machine_learning: '机器学习',
    infrastructure: '基础设施',
    testing: '测试',
    maintenance: '维护',
    research: '研究',
    other: '其他'
  }
  return categoryMap[category] || category
}

// 组件挂载时获取数据
onMounted(async () => {
  console.log('项目页面初始化开始')
  
  // 获取优先级数据
  await fetchPriorities()
  
  // 获取用户列表，用于负责人显示
  await fetchUsers()
  
  // 初始化状态数据
  console.log('开始获取项目状态数据...')
  try {
    await stateStore.fetchStates({ module_type: ModuleType.PROJECT })
    console.log('项目状态数据获取成功:', stateStore.states)
  } catch (error) {
    console.error('获取项目状态数据失败:', error)
  }
  
  // 先获取统计数据
  try {
    await projectStatsStore.fetchStats()
  } catch (error) {
    console.error('获取项目统计数据失败:', error)
  }
  
  // 再获取项目列表
  await fetchProjects()
  
  console.log('项目页面初始化完成')
  initialLoading.value = false
})
</script>

<style scoped>
.projects-container {
  padding: 20px;
  background: var(--bg-secondary);
  min-height: 100vh;
  transition: background-color 0.3s ease, color 0.3s ease;
  color: var(--text-primary);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 4px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.collapse-btn {
  transition: all 0.3s ease;
  border: 1px solid #e4e7ed;
}

.collapse-btn:hover {
  background-color: #f5f7fa;
  border-color: #409eff;
  color: #409eff;
}

.header-title-wrapper {
  display: flex;
  flex-direction: column;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: var(--text-primary);
  transition: color 0.3s ease;
}

.page-description {
  color: var(--text-secondary);
  margin: 5px 0 0 0;
  transition: color 0.3s ease;
}

/* 主内容区域布局 */
.main-content {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

/* 左侧筛选栏 */
.filter-sidebar {
  width: 320px;
  flex-shrink: 0;
  position: sticky;
  top: 20px;
  max-height: calc(100vh - 100px);
  overflow-y: auto;
  overflow-x: hidden;
}

.filter-sidebar::-webkit-scrollbar {
  width: 6px;
}

.filter-sidebar::-webkit-scrollbar-track {
  background: transparent;
}

.filter-sidebar::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.filter-sidebar::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}

.filter-card {
  border-radius: 12px;
  border: 1px solid var(--border-color-light);
  box-shadow: var(--shadow-sm);
  background-color: var(--bg-card);
  transition: all 0.3s ease;
}

.filter-card:hover {
  box-shadow: var(--shadow-md);
  border-color: var(--border-color);
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.filter-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  transition: color 0.3s ease;
}

.filter-title .el-icon {
  color: #409eff;
  font-size: 18px;
}

.reset-all-btn {
  color: #909399;
  transition: all 0.3s ease;
}

.reset-all-btn:hover {
  color: #409eff;
}

.filter-content {
  padding: 4px 0;
}

.filter-group {
  margin-bottom: 20px;
}

.filter-group:last-child {
  margin-bottom: 0;
}

.filter-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-secondary);
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--border-color-extra-light);
  transition: color 0.3s ease, border-color 0.3s ease;
}

.filter-label .el-icon {
  color: #909399;
  font-size: 16px;
}

.filter-item {
  margin-bottom: 16px;
}

.filter-item:last-child {
  margin-bottom: 0;
}

.filter-item-label {
  display: block;
  font-size: 13px;
  color: var(--text-secondary);
  margin-bottom: 8px;
  font-weight: 500;
  transition: color 0.3s ease;
}

.filter-input,
.filter-select,
.filter-date {
  width: 100%;
  transition: all 0.3s ease;
}

.filter-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.filter-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.filter-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.filter-select :deep(.el-input__wrapper) {
  border-radius: 8px;
}

.filter-collapse {
  margin-top: 20px;
  border: none;
}

.filter-collapse :deep(.el-collapse-item__header) {
  padding: 12px 0;
  border-bottom: 1px solid #f0f2f5;
  font-weight: 600;
  color: #606266;
  transition: all 0.3s ease;
}

.filter-collapse :deep(.el-collapse-item__header:hover) {
  color: #409eff;
}

.collapse-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.collapse-title .el-icon {
  color: #909399;
  font-size: 16px;
}

.filter-collapse :deep(.el-collapse-item__content) {
  padding: 16px 0 0 0;
}

.filter-actions {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #f0f2f5;
}

.export-btn {
  border-radius: 8px;
  height: 40px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

.export-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

/* 右侧主内容区 */
.content-area {
  flex: 1;
  min-width: 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.content-area.full-width {
  max-width: 100%;
}

/* 侧边栏动画 */
.slide-left-enter-active,
.slide-left-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.slide-left-enter-from {
  opacity: 0;
  transform: translateX(-20px);
  width: 0;
  margin-right: 0;
}

.slide-left-leave-to {
  opacity: 0;
  transform: translateX(-20px);
  width: 0;
  margin-right: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.view-controls {
  display: flex;
  align-items: center;
}

.card-view {
  min-height: 400px;
  position: relative;
}

.card-view .el-row {
  animation: fadeInCards 0.5s ease-out;
}

@keyframes fadeInCards {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.project-card-col {
  animation: cardSlideIn 0.4s ease-out backwards;
}

.project-card-col:nth-child(1) { animation-delay: 0.05s; }
.project-card-col:nth-child(2) { animation-delay: 0.1s; }
.project-card-col:nth-child(3) { animation-delay: 0.15s; }
.project-card-col:nth-child(4) { animation-delay: 0.2s; }
.project-card-col:nth-child(5) { animation-delay: 0.25s; }
.project-card-col:nth-child(6) { animation-delay: 0.3s; }

@keyframes cardSlideIn {
  from {
    opacity: 0;
    transform: translateY(30px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.project-card-col {
  margin-bottom: 12px;
}

/* 旧样式已移除，使用下方优化后的紧凑样式 */

.table-view {
  min-height: 400px;
  position: relative;
}

.table-view :deep(.el-table) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.table-view :deep(.el-table:hover) {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.table-view :deep(.el-table__row) {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.table-view :deep(.el-table__row:hover) {
  background-color: #f8f9fa !important;
}

.table-view :deep(.el-table__row) {
  animation: fadeInRow 0.3s ease-out;
}

@keyframes fadeInRow {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.table-view :deep(.el-table th) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  font-weight: 600;
  color: #495057;
  border-bottom: 2px solid #dee2e6;
}

.table-view :deep(.el-table td) {
  border-bottom: 1px solid #f0f2f5;
  transition: all 0.2s ease;
}

.table-view :deep(.el-table__row:hover td) {
  border-bottom-color: #e0e7ff;
}

.project-name-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.name-wrapper {
  display: flex;
  align-items: center;
  gap: 4px;
  flex: 1;
  min-width: 0;
}

.project-name-cell .name {
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.project-title-link {
  cursor: pointer;
  user-select: none;
  transition: all 0.3s ease;
}

.project-title-link:hover {
  color: #409eff;
  text-decoration: underline;
}

.pin-button-table {
  flex-shrink: 0;
  padding: 2px;
  font-size: 14px;
  transition: all 0.2s ease;
  color: #909399;
}

.pin-button-table.pin-button-active {
  color: #e6a23c !important;
}

.pin-button-table.pin-button-active :deep(.el-icon) {
  color: #e6a23c !important;
}

.pin-button-table.pin-button-active:hover {
  color: #cf9236 !important;
  transform: scale(1.1);
}

.pin-button-table.pin-button-active:hover :deep(.el-icon) {
  color: #cf9236 !important;
}

.pin-button-table.pin-button-inactive {
  color: #c0c4cc !important;
}

.pin-button-table.pin-button-inactive :deep(.el-icon) {
  color: #c0c4cc !important;
}

.pin-button-table.pin-button-inactive:hover {
  color: #e6a23c !important;
  transform: scale(1.1);
}

.pin-button-table.pin-button-inactive:hover :deep(.el-icon) {
  color: #e6a23c !important;
}

.progress-cell {
  display: flex;
  align-items: center;
}

.progress-text {
  margin-left: 8px;
  font-size: 12px;
  color: #606266;
  min-width: 35px;
}

.tags-cell {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.form-help {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}

/* 项目卡片样式优化 - 3D动态效果设计 */
.project-card {
  border-radius: 16px;
  border: 1px solid rgba(226, 232, 240, 0.8);
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  position: relative;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  transform-style: preserve-3d;
  perspective: 1000px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.project-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(147, 197, 253, 0.05) 0%, rgba(216, 180, 254, 0.05) 100%);
  z-index: 0;
  pointer-events: none;
  opacity: 0;
  transition: opacity 0.4s ease;
  border-radius: 16px;
}

.project-card::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  transform: scaleX(0);
  transform-origin: left;
  transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 1;
}

.project-card-hover {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  transform-origin: center;
}

.project-card-hover:hover {
  transform: translateY(-8px) rotateX(2deg) rotateY(-2deg) scale(1.02);
  box-shadow: 
    0 20px 40px rgba(0, 0, 0, 0.12),
    0 8px 16px rgba(0, 0, 0, 0.08),
    0 0 0 1px rgba(99, 102, 241, 0.1);
  border-color: rgba(99, 102, 241, 0.3);
}

.project-card-hover:hover::before {
  opacity: 1;
}

.project-card-hover:hover::after {
  transform: scaleX(1);
}

.project-card-hover:hover .project-title {
  color: #6366f1;
  transform: translateX(2px);
}

.project-card-hover:hover .el-button {
  transform: translateY(-2px) scale(1.05);
}

.project-card-hover:hover .project-header {
  border-bottom-color: rgba(167, 139, 250, 0.3);
}

.project-card-hover:hover .project-progress {
  transform: scale(1.02);
}

.project-card-hover:hover .stats-icon-wrapper {
  animation: iconFloat 2s ease-in-out infinite;
}

@keyframes iconFloat {
  0%, 100% {
    transform: translateY(0) rotate(0deg);
  }
  50% {
    transform: translateY(-4px) rotate(5deg);
  }
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(241, 245, 249, 0.8);
  transition: border-color 0.3s ease;
  position: relative;
  z-index: 1;
  gap: 8px;
}

.project-status-tags {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-shrink: 0;
}

.project-title-wrapper {
  display: flex;
  align-items: center;
  gap: 6px;
  flex: 1;
  min-width: 0;
}

.project-title {
  font-size: 15px;
  font-weight: 600;
  color: #1e293b;
  line-height: 1.4;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  display: box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  box-orient: vertical;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  min-width: 0;
  position: relative;
  z-index: 2;
  cursor: pointer;
  user-select: none;
}

.project-title:hover {
  color: #6366f1;
  text-decoration: underline;
}

.pin-button {
  flex-shrink: 0;
  padding: 4px;
  font-size: 16px;
  transition: all 0.2s ease;
  color: #909399;
}

.pin-button-active {
  color: #e6a23c !important;
}

.pin-button-active :deep(.el-icon) {
  color: #e6a23c !important;
}

.pin-button-active:hover {
  color: #cf9236 !important;
  transform: scale(1.1);
}

.pin-button-active:hover :deep(.el-icon) {
  color: #cf9236 !important;
}

.pin-button-inactive {
  color: #c0c4cc !important;
}

.pin-button-inactive :deep(.el-icon) {
  color: #c0c4cc !important;
}

.pin-button-inactive:hover {
  color: #e6a23c !important;
  transform: scale(1.1);
}

.pin-button-inactive:hover :deep(.el-icon) {
  color: #e6a23c !important;
}

.project-description {
  font-size: 12px;
  color: #64748b;
  line-height: 1.5;
  margin-bottom: 10px;
  min-height: 36px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  display: box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  box-orient: vertical;
  position: relative;
  z-index: 1;
}

.project-meta-compact {
  margin-bottom: 10px;
  position: relative;
  z-index: 1;
}

.meta-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
  gap: 8px;
}

.meta-row:last-child {
  margin-bottom: 0;
}

.meta-item-compact {
  display: flex;
  align-items: center;
  font-size: 11px;
  color: #94a3b8;
  gap: 4px;
  opacity: 0.9;
  transition: opacity 0.3s ease;
  flex: 1;
  min-width: 0;
}

.meta-item-compact span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.priority-tag {
  flex-shrink: 0;
}

.project-card-hover:hover .meta-item-compact {
  opacity: 1;
}

.project-tags {
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  position: relative;
  z-index: 1;
}

.tag-item {
  font-size: 10px;
  padding: 2px 8px;
  height: 20px;
  line-height: 16px;
  border-radius: 10px;
  background: rgba(241, 245, 249, 0.8);
  transition: all 0.3s ease;
}

.project-card-hover:hover .tag-item {
  background: rgba(241, 245, 249, 1);
  transform: scale(1.05);
}

.project-progress {
  margin-bottom: 10px;
  position: relative;
  z-index: 1;
  transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.progress-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
  font-size: 11px;
  color: #64748b;
  font-weight: 500;
}

.progress-percentage {
  font-weight: 600;
  color: #4f46e5;
  font-size: 12px;
}

.el-progress-bar__outer {
  background-color: rgba(241, 245, 249, 0.8);
  border-radius: 10px;
  overflow: hidden;
  height: 6px !important;
}

.el-progress-bar__inner {
  border-radius: 12px;
  transition: width 1s cubic-bezier(0.4, 0, 0.2, 1);
}

.project-card-hover:hover .el-progress-bar__inner {
  box-shadow: 0 0 12px rgba(99, 102, 241, 0.3);
}

.project-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 4px;
  margin-top: auto;
  padding-top: 10px;
  border-top: 1px solid rgba(241, 245, 249, 0.8);
  position: relative;
  z-index: 1;
}

.project-actions .el-button {
  font-size: 11px;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.2s ease;
  font-weight: 500;
  min-width: auto;
}

.project-actions .el-button:hover {
  background-color: rgba(99, 102, 241, 0.1);
  color: #6366f1;
}

/* 标签样式增强 */
.project-header .el-tag {
  border-radius: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
  padding: 2px 8px;
  font-size: 11px;
}

.project-card-hover:hover .project-header .el-tag {
  transform: scale(1.05);
}

/* 响应式优化 */
@media (max-width: 1400px) {
  .project-card-col {
    flex: 0 0 33.333333%;
    max-width: 33.333333%;
  }
}

@media (max-width: 992px) {
  .project-card-col {
    flex: 0 0 50%;
    max-width: 50%;
  }
  
  .project-card-hover:hover {
    transform: translateY(-6px) rotateX(1deg) scale(1.01);
  }
}

@media (max-width: 768px) {
  .project-card-col {
    flex: 0 0 100%;
    max-width: 100%;
  }
  
  .project-card-hover:hover {
    transform: translateY(-4px) scale(1.01);
  }
}


/* 状态和优先级选项样式 */
.status-option,
.priority-option {
  padding: 8px 12px;
  transition: all 0.2s ease;
}

.status-option:hover,
.priority-option:hover {
  background-color: #f5f7fa;
}

/* 状态颜色样式 */
.status-option.status-active {
  color: #67c23a;
}

.status-option.status-completed {
  color: #409eff;
}

.status-option.status-pending {
  color: #e6a23c;
}

.status-option.status-cancelled {
  color: #909399;
}

.status-option.status-overdue {
  color: #f56c6c;
}

/* 优先级颜色样式 */
.priority-option.priority-high {
  color: #f56c6c;
}

.priority-option.priority-medium {
  color: #e6a23c;
}

.priority-option.priority-low {
  color: #67c23a;
}

.priority-option.priority-urgent {
  color: #ff4d4f;
}


/* 响应式设计 */
@media (max-width: 1200px) {
  .filter-sidebar {
    width: 280px;
  }
  
  .stats-card {
    height: 90px;
  }
  
  .stats-number {
    font-size: 22px;
  }
  
  .stats-icon-wrapper {
    width: 44px;
    height: 44px;
  }
  
  .stats-icon {
    font-size: 22px;
  }
}

@media (max-width: 992px) {
  .filter-sidebar {
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    z-index: 1000;
    background: white;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
    max-height: 100vh;
    overflow-y: auto;
  }
  
  .content-area {
    margin-left: 0;
  }
  
  .content-area.full-width {
    width: 100%;
  }
  
  .stats-card {
    height: 85px;
  }
  
  .stats-number {
    font-size: 20px;
  }
  
  .stats-label {
    font-size: 11px;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .header-right {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    gap: 8px;
  }
  
  .filter-sidebar {
    width: 100%;
    max-width: 320px;
  }
  
  .stats-section {
    margin-bottom: 16px;
  }
  
  .stats-card {
    height: 80px;
  }
  
  .stats-content {
    gap: 10px;
  }
  
  .stats-icon-wrapper {
    width: 40px;
    height: 40px;
  }
  
  .stats-icon {
    font-size: 20px;
  }
  
  .stats-number {
    font-size: 18px;
  }
  
  .stats-label {
    font-size: 10px;
  }
  
  .project-card-hover:hover {
    transform: translateY(-4px) scale(1.01);
  }
}

@media (max-width: 576px) {
  .stats-card {
    height: 75px;
  }
  
  .stats-icon-wrapper {
    width: 36px;
    height: 36px;
  }
  
  .stats-icon {
    font-size: 18px;
  }
  
  .stats-number {
    font-size: 16px;
  }
  
  .stats-label {
    font-size: 9px;
  }
}

</style>